package com.kaigejava.webmaginc;

import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * csdn文章爬去demo
 * @author kaigejava
 */
public class CsdnNavJava implements PageProcessor {

    public void process(Page page) {


        ////*[@id="feedlist_id"]/li[2]/div/div[1]/h2/a
        List<String> list= page.getHtml().xpath("//*[@id='feedlist_id']/").all();
        if(!list.isEmpty()) {
            for(int i = 0;i<list.size();i++){
                String string = list.get(i);
                String id = page.getHtml().xpath("//*[@id=\"feedlist_id\"]/li["+(i+1)+"]/@data-id").toString();
                   String authUrl =  page.getHtml().xpath("//*[@id=\"feedlist_id\"]/li["+(i+1)+"]/div/dl/dd/a/@href").toString();
                  if(StringUtils.isNotBlank(authUrl)){
                      String articleUrl= authUrl+"/article/details/"+id;
                      System.out.println("==访问文章详情id:"+articleUrl);
                      page.addTargetRequest(articleUrl);
                  }


            }

        }
        System.out.println("pageUrl:"+page.getRequest().getUrl());
        String article="/article/details/";
       if(page.getRequest().getUrl().contains(article)) {
            String title = page.getHtml().xpath("//*[@id=\"mainBox\"]/main/div[1]/div/div/div[1]/h1").toString();
           System.out.println("标题:"+title.replaceAll("<h1 class=\"title-article\">","").replaceAll("</h1>",""));
            String  content =  page.getHtml().xpath("//*[@id=\"article_content\"]").toString();
        //   System.out.println("内容:"+content);
        }


    }

    public Site getSite() {
        return Site.me().setSleepTime(100).setRetryTimes(3);
    }

    public static void main(String[] args) {
        Spider.create(new CsdnNavJava()).addUrl("https://blog.csdn.net/nav/java").addRequest().run();
    }

}
